package com.study.chapter05.operator.transform;

import com.study.entity.Event;
import com.study.chapter05.source.ClickSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/7/28 10:48
 */
public class FlatMapOperatorTest {

    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //使用自定义的SourceFunction，注意对于自定义的直接继承SourceFunction的，并行度只能设置为1，否则会抛出异常
        DataStreamSource<Event> stream = env.addSource(new ClickSource()).setParallelism(1);

        //1.自定义FlatMapFunction
        SingleOutputStreamOperator<String> result1 = stream.flatMap(new MyFlatMapFunction());

        //2.使用lambda
        SingleOutputStreamOperator<String> result2 = stream.flatMap((Event event, Collector<String> collector) -> {
            if (StringUtils.equals(event.getUser(), "Bob")) {
                collector.collect(event.getUser());
                collector.collect(event.getUrl());
            } else if (StringUtils.equals(event.getUser(), "Mary")) {
                collector.collect(event.getUrl());
            }
        }).returns(Types.STRING);

        result1.print("MyFlatMap：");
        result2.print("lambda：");

        env.execute();
    }

    public static class MyFlatMapFunction implements FlatMapFunction<Event,String> {

        @Override
        public void flatMap(Event event, Collector<String> collector) throws Exception {
            if (StringUtils.equals(event.getUser(),"Bob")){
                collector.collect(event.getUser());
                collector.collect(event.getUrl());
            }else if (StringUtils.equals(event.getUser(),"Alice")){
                collector.collect(event.getUrl());
            }
        }
    }
}
